package com.lagou.homework.clientserverchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author Rentaian
 */
public class ClientTest2 {

    public static void main(String[] args) {
        //创建Socket对象并提供服务的主机名和端口号
        Socket s = null;
        //提供打印流向服务器发送消息
        PrintStream ps = null;
        //提供字符缓冲输入流用于接收服务器发送而来的消息
        BufferedReader br = null;
        //创建Scanner对象用于键盘输入
        Scanner sc = null;
        try {
            s = new Socket("127.0.0.1",8888);
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            ps = new PrintStream(s.getOutputStream());
            sc = new Scanner(System.in);
            while(true) {
                System.out.println("请输入要向服务器发送的消息：");
                //从键盘输入一个字符串
                String string = sc.next();
                ps.println(string);
                System.out.println("客户端发送数据成功");
                if ("bye".equalsIgnoreCase(string)) {
                    System.out.println("聊天结束！");
                    break;
                }
                String str1 = br.readLine();
                System.out.println("接收到从服务器发来的消息: " + str1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != sc) {
                sc.close();
            }
            if(null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != ps) {
                ps.close();
            }
        }
    }
}
